package com.cskaoyan.filter;


import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.exception.InfoExpiredException;
import com.cskaoyan.exception.NoInfoException;
import com.cskaoyan.util.AuthenticationUtil;
import com.cskaoyan.util.ResponseUtil;
import com.cskaoyan.util.WdConstant;
import com.cskaoyan.util.WdTokenHolder;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author stone
 * @date 2023/03/17 14:16
 */
@WebFilter("/*")
public class AuthenticationInfoFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "*");
        response.addHeader("Access-Control-Allow-Headers", "*");
        if (request.getMethod().equals("OPTIONS") || request.getRequestURI().endsWith("/login")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        if (request.getRequestURI().startsWith("/wx/storage/fetch")) {
            filterChain.doFilter(request,response);
            return;
        }

        String token = request.getHeader(WdConstant.MARKET_TOKEN);
        AuthenticationUtil.setToken(token);
        try {
            Object info = WdTokenHolder.getInfo(token);
            filterChain.doFilter(servletRequest, servletResponse);
        } catch (NoInfoException e) {
            e.printStackTrace();
            ResponseUtil.responseJson(response, BaseRespVo.unAuthc());
        } catch (InfoExpiredException e) {
            e.printStackTrace();
            ResponseUtil.responseJson(response,BaseRespVo.expired());
        }
    }

    @Override
    public void destroy() {

    }


}
